package com.spider.im.chat.server;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.im.chat.entity.ChatGroupUser;
import com.spider.im.chat.req.ChatMessage;

import com.spider.im.chat.service.ChatGroupUserService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;


import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class MessageService {

    @Resource
    public ChatGroupUserService chatGroupUserService;


    private final ConcurrentHashMap<Long, Channel> activeChannels = new ConcurrentHashMap<>();

    /**
     * 处理请求，将消息转换成消息对象
     * @param request
     * @param channel
     * @return
     */
    public void processRequest(String request, Channel channel) {
        ChatMessage chatMessage = JSONUtil.toBean(request, ChatMessage.class);
        if (chatMessage == null) {
            log.warn("消息解析失败 Invalid request: {}", request);
            return;
        }
//
//        Long userId = chatMessage.getUserId();
//        if (userId == null){
//            return;
//        }
//        switch (chatMessage.getMessageType()) {
//            case LOGIN:
//                //
//                activeChannels.put(userId, channel);
//                break;
//            case LOGOUT:
//                //退出登陆关闭通道
//                Channel channel1 = activeChannels.get(userId);
//                if (channel1 != null){
//                    channel1.close();
//                }
//                activeChannels.remove(userId);
//                break;
//            case SEND_MESSAGE:
//                sendMessage(chatMessage);
//                break;
//        }

    }

    public void sendMessage(ChatMessage chatMessage) {
//
//        Long targetUserId = chatMessage.getTargetUserId();
//        if (targetUserId != null) {
//            Channel targetChannel = activeChannels.get(targetUserId);
//            if (targetChannel != null && targetChannel.isActive()) {
//                targetChannel.writeAndFlush(new TextWebSocketFrame(chatMessage.getMessage()));
//            } else {
//                log.warn("User {} is offline. Message not sent.", targetUserId);
//            }
//        }
//        //如果是群聊
//        if (chatMessage.getTargetGroupId() != null) {
//            //获取群聊的在线用户
//            List<ChatGroupUser> chatGroupUserList = chatGroupUserService.list(new LambdaQueryWrapper<ChatGroupUser>().eq(ChatGroupUser::getGroupId, chatMessage.getTargetGroupId()));
//            if (CollectionUtil.isEmpty(chatGroupUserList)) {
//                log.warn("组TargetGroupId {} 没有人. Message not sent.", chatMessage.getTargetGroupId());
//                return;
//            }
//            //遍历群聊的在线用户,发送消息
//            chatGroupUserList.forEach(chatGroupUser -> {
//                Channel targetChannel = activeChannels.get(chatGroupUser.getUserId());
//                if (targetChannel != null && targetChannel.isActive()) {
//                    log.info("给用户发送消息 {}.", chatGroupUser.getUserId());
//                    targetChannel.writeAndFlush(new TextWebSocketFrame(chatMessage.getMessage()));
//                }
//            });
//        }
    }

}